import { utilities as nestWinstonModuleUtilities } from 'nest-winston';
import * as winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';

export const winstonConfig = {
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        // winston.format.timestamp(),
        winston.format.printf(({ timestamp, level, message, stack }) => {
          return `${timestamp} ${level}: ${message}${stack ? `\n${stack}` : ''}`;
        }),
        winston.format.timestamp({
          format: () => new Date().toLocaleString('zh-CN'),
        }),
        winston.format.ms(),
        nestWinstonModuleUtilities.format.nestLike('HTTP', {
          colors: true,
          prettyPrint: true,
        }),
      ),
    }),
    new DailyRotateFile({
      filename: 'logs/access-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: false,
      maxSize: '20m',
      maxFiles: '14d',
      level: 'info',
      format: winston.format.combine(
        winston.format.timestamp({
          format: () => new Date().toLocaleString('zh-CN'),
        }),
        winston.format.printf(({ timestamp, url, status, method, level, message }) => {
          if (level === 'error') {
            return `${timestamp} ${level}: ${url} ${status} ${method} ${message}`;
          }
          return `${timestamp} ${level}: ${message}`;
        }),
        // winston.format.json(),
      ),
    }),
    new DailyRotateFile({
      filename: 'logs/error-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: false,
      maxSize: '20m',
      maxFiles: '30d',
      level: 'error',
      format: winston.format.combine(
        winston.format.timestamp({
          format: () => new Date().toLocaleString('zh-CN'),
        }),
        winston.format.printf(({ timestamp, url, status, method, level, message, stack }) => {
          return `${timestamp} ${level}: ${url} ${status} ${method} ${message}${stack ? `\n${stack}` : ''}`;
        }),
        // winston.format.json(),
      ),
    }),
  ],
};

export const winstonLogger = winston.createLogger(winstonConfig);
